<template>
    <div class="orderPay_content">
      <jm-head ref="head"></jm-head>
        <div class="orderPay_fixed box" v-if="orderInfo.order_status === 2">
            <div class="fl">剩余支付时间：<van-count-down :time = "orderInfo.has_time" format="mm 分钟 ss 秒" /></div>
            <button class="fr qx" @click="cancelOrder">取消订单</button>
        </div>
        <div class="orderPay_fixed box" v-else>
            <div class="fl">{{tips.left}}</div>
            <span class="f2">{{tips.right}}</span>
            <button @click="accepter" class="fr qx" v-if="orderInfo.order_status === 4">确认收货</button>
        </div>
        <div class="orderPay_getAddr box" v-if="showAddress === 1">
            <div class="fgx_img">
                <img src="@/assets/img/fgx.jpg" alt="分割线">
            </div>
            <van-cell
                :title="addressInfo.hasAddress === true ? addressInfo.accepter_name : '尚未选择收货地址'"
                :label="addressInfo.detail"
                :is-link="orderInfo.order_status === 2"
                center
                @click="useAddr"
            />
            <div class="fgx_img">
                <img src="@/assets/img/fgx.jpg" alt="分割线">
            </div>
        </div>
        <van-cell-group title="商品信息" style="padding: .2rem 0;">
            <van-card
                v-for="item of orderItem"
                :key = "item.id"
                :num="item.goods_quantity"
                :price="item.pay_price/100"
                :origin-price="item.base_price/100"
                :title="item.good_title"
                style="background: #fff;"
                :thumb="item.good_logo"
            />
        </van-cell-group>
        <van-cell-group title="价格信息">
            <van-cell title="商品总价" :value="'￥' + orderInfo.pay_price" />
                <van-cell :title="'积分抵扣（已抵扣' + orderInfo.jf_price/100 + '元）'">
                <van-switch :value="orderInfo.jf_price !== 0" size="22px" active-color="#d64532" @input="useJfAction" />
            </van-cell>
            <van-cell title="应付总金额" :value="'￥' + (orderInfo.pay_price + orderInfo.express_price - orderInfo.jf_price/100)" />
        </van-cell-group>
        <van-cell-group title="收货信息">
            <van-cell title="发货方式" :value="orderInfo.express_type" :is-link="orderInfo.order_status === 2" @click="selectExpress" />
            <van-cell title="运费" :value="'￥' + orderInfo.express_price" />
        </van-cell-group>
        <van-cell-group title="物流信息" v-if="orderInfo.order_status === 4 || orderInfo.order_status === 5">
            <van-cell v-for="item in orderInfo.expressArr" :key="item" @click="see(orderInfo.express_type, item)" title="运单号" :value="item" is-link />
        </van-cell-group>
        <van-cell-group title="订单信息">
            <van-cell title="订单号" :value="orderInfo.order_code" class="order_info" />
            <van-cell title="订单状态" :value="orderInfo.status_title" />
            <van-cell center title="买家信息" size="larze"  class="info">
                <div style="margin-right: .2rem">
                    <span>{{userInfo.true_name === ''? userInfo.nickname : userInfo.nickname}}</span>
                    <br />
                    <span>{{userInfo.phone}}</span>
                </div>
                <template #right-icon>
                    <van-icon :name="userInfo.avatar" style="line-height: inherit;" />
                </template>
            </van-cell>

            <van-cell title="下单时间" :value="orderInfo.created_at" />
            <van-cell v-if="orderInfo.order_status === 3 || orderInfo.order_status === 4 || orderInfo.order_status === 5" title="支付时间" :value="orderInfo.pay_at" />
            <van-cell v-if="orderInfo.order_status === 4 || orderInfo.order_status === 5" title="发货时间" :value="orderInfo.send_at" />
            <van-cell v-if="orderInfo.order_status === 5" title="收货时间" :value="orderInfo.accept_at" />
            <van-cell v-if="orderInfo.order_status === 0 || orderInfo.order_status === 1" title="取消时间" :value="orderInfo.cancel_at" />
        </van-cell-group>

        <div style="position: fixed;bottom: 10px;width: 80%;margin-left: 10%;" v-if="orderInfo.order_status === 2">
          <van-button type="primary" round block style="background: #ee0a24;border-color: #ee0a24;" @click="selectPay">立即支付</van-button>
        </div>

        <van-action-sheet
          v-model="showExpressTypeModel"
          :actions="expressTypeArr"
          cancel-text="取消"
          :close-on-click-action="true"
          :close-on-popstate="true"
          @select="selectExpressType"
          description="选择邮寄方式"
        />

        <van-action-sheet
          v-model="showPayTypeModel"
          :actions="payTypeArr"
          cancel-text="取消"
          :close-on-click-action="true"
          :close-on-popstate="true"
          @select="selectPayType"
          description="选择支付方式"
        />

        <van-action-sheet v-model="showPasKey" title="输入支付密码">
            <div class="content_div box">
                <van-password-input
                :value="passwordVal"
                :focused="showKey"
                @focus="showKey = true"
                />
                <!-- 数字键盘 -->
                <van-number-keyboard
                :show="showKey"
                @input="onInput"
                @delete="onDelete"
                @blur="showKey = true"
                />

            </div>
        </van-action-sheet>
    </div>
</template>
<script>
import Vue from 'vue';
// import { Toast, Dialog,Cell, CellGroup,Card,Switch,Button, ActionSheet, PasswordInput, NumberKeyboard, useCountDown } from 'vant'
import { detail, useJf, changeExpress, isSetPay, pay, cancel, accepter } from "@/api/order"
import JmHead from '../head/head'
// import wx from 'weixin-js-sdk';
import { ybPrePay,payOrder } from "@/api/pay"
import Vant from 'vant'
import { Toast, Dialog} from 'vant'

Vue.use(Vant)
// Vue.use(Cell).use(CellGroup).use(Card).use(Switch).use(Button).use(ActionSheet).use(PasswordInput).use(NumberKeyboard)
export default {
    name: 'orderDetail',
    components: {
        JmHead
    },
    data () {
        return {
            id: 0,
            orderItem: {},
            userInfo: {},
            showAddress: 0,
            addressInfo: {
                hasAddress: false
            },
            orderInfo: {
                express_price: 0,
                pay_price: 0,
                jf_price: 0,
            },
            tips: {
                left: '',
                right: ''
            },
            express_type: {},
            expressTypeArr: [],
            showExpressTypeModel: false,

            showPayTypeModel: false,
            payTypeArr: [
                {name: '余额支付'},
                {name: '微信支付'},
            ],

            time: 30 * 60 * 1000,
            activeNames: ['1'],
            showPasKey: false,
            passwordVal: '',
            showKey: true,
        }
    },
    methods: {
        getDetail() {
            const toast = Toast.loading({
                  message: '数据加载中...',
                  forbidClick: true,
            })
            detail({id: this.id}).then(res => {
                this.expressTypeArr = []
                toast.clear()
                this.orderItem = res.data.order_item
                this.userInfo = res.data.user
                this.showAddress = res.data.address_use
                this.express_type = res.data.express_type
                this.orderInfo = res.data.order
                this.orderInfo.pay_price = this.orderInfo.pay_price / 100
                this.orderInfo.express_type = this.express_type[this.orderInfo.express_type]
                this.tips = res.data.tips
                const expressArr = this.orderInfo.express_number.split('-')
                this.orderInfo.expressArr = expressArr.filter(res => {
                    return res && res.trim();
                })
                switch (this.orderInfo.expressArr) {
                    case 1:
                        this.orderInfo.status_title = '已取消'
                        break;
                    case 2:
                        this.orderInfo.status_title = '待付款'
                        break;
                    case 3:
                        this.orderInfo.status_title = '待发货'
                        break;
                    case 4:
                        this.orderInfo.status_title = '待收货'
                        break;
                    case 5:
                        this.orderInfo.status_title = '已收货'
                        break;
                }
                for(const index in this.express_type) {
                    const obj = {
                        index: index,
                        name: this.express_type[index]
                    }
                    this.expressTypeArr.push(obj)
                }
                if (res.data.order.accepter_name !== '') {
                    this.addressInfo.hasAddress = true
                    this.addressInfo.accepter_name = res.data.order.accepter_name
                    this.addressInfo.accepter_phone = res.data.order.accepter_phone
                    this.addressInfo.detail = res.data.order.province_name + res.data.order.city_name + res.data.order.district_name + res.data.order.detail_address
                }
            })
        },
        useAddr() {
            if (this.orderInfo.order_status !== 2) {
                return
            }
            this.$router.push({path: '/addr', query: {order_id: this.id}})
        },
        selectExpress() {
            if (this.orderInfo.order_status !== 2) {
                return
            }
            if (this.orderInfo.national_code === 0) {
                Toast.fail({message: '请先选择地址', duration: 2000})
                return
            }
            this.showExpressTypeModel = true
        },
        selectExpressType(action, index) {
            changeExpress({id: this.id, national_code: this.orderInfo.national_code, express_type: action.index}).then(res => {
                this.getDetail()
            })
        },
        useJfAction(e) {
            if (this.orderInfo.order_status !== 2) {
                return
            }
            const msg = e ? '确定使用积分？' : '确定取消使用积分？'
            Dialog.confirm({
              message: msg,
            }).then(() => {
                useJf({id: this.id, type: e ? 1 : 0}).then(res => {
                    if(res.code === 20000) {
                      if (res.data === 0 && this.orderInfo.jf_price == 0) {
                          Toast.fail({message: '无可用积分', duration: 2000})
                          return
                      }
                      this.getDetail()
                    }
                })
            }).catch(() => {
            })
        },
        selectPay() {
          pay({id: this.id, payType: 0}).then(res => {
              if (res.code !== 20000) {
                  Toast.fail({message: res.info, duration: 2000})
              } else {
                this.showPayTypeModel = true
              }
          })

        },
        // 密码键盘
        onInput(key) {
            let that = this;
            that.passwordVal = (that.passwordVal + key).slice(0, 6);
            if (that.passwordVal.length === 6) {
                let password_pay = that.passwordVal
                console.log(password_pay);
                pay({id: this.id, payType: 1, password_pay: password_pay}).then(res => {
                  console.log(res);
                    if (res.code !== 20000) {
                        this.passwordVal = ''
                        Toast.fail({message: res.info, duration: 2000})
                    } else {
                      this.passwordVal = ''
                      this.getDetail();
                      this.showPasKey = false;
                      Toast.success({message: res.info, duration: 2000})
                      this.$router.push({path: '/person'})
                    }
                })
            }
        },
        onDelete() {
            this.passwordVal = this.passwordVal.slice(0, this.passwordVal.length - 1);
        },
        selectPayType(action, index) {
            if (index === 0) {
                isSetPay({}).then(res => {
                    if(res.data === 1) {
                        this.showPasKey = true;
                    } else {
                        this.$router.push({path: '/password/pay'})
                    }
                })
            }else{
                const toast = Toast.loading({
                  duration: 0,
                  message: '微信支付调起中...',
                });
                let price = this.orderInfo.pay_price + this.orderInfo.express_price - this.orderInfo.jf_price/100
                //原生微信支付
                payOrder({money: price, url: location.href,payType: 2,id: this.id}).then(res=>{
                    if(res.code === 20000) {
                      this.pay(res.data, toast)
                    } else {
                      Toast.fail({message: res.data.info, duration: 2000})
                    }
                })
                //ybPrePay({money: price, url: location.href.split("#")[0],payType: 2,id: this.id}).then(res=>{
                //    console.log(res.data.result);
                //    var result = eval("(" + res.data.result.prePayTn + ")")
                //    console.log(result);
                //    if(res.code === 20000) {
                //      this.pay(result, toast, res.data.signature)
                //    } else {
                //      Toast.fail({message: res.data.info, duration: 2000})
                //    }
                //})
            }
        },
        //前端调起微信支付
        pay(res, toast) {
            toast.clear()
            const that = this
            wx.config({
              debug: false,
              appId: res.appid,
              timestamp: res.timestamp,
              nonceStr: res.noncestr,
              signature: res.signature,
              jsApiList: ['openAddress']
            });

            wx.ready(function() {
                wx.chooseWXPay({
                  timestamp: res.timestamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                  nonceStr: res.noncestr, // 支付签名随机串，不长于 32 位
                  package: res.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
                  signType: 'MD5', // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
                  paySign: res.paySign, // 支付签名
                  success: function (res) {
                    // 支付成功后的回调函数
                    that.$router.go(-1);
                  }
                });
            })
        },

        cancelOrder() {
            const that = this
            Dialog.confirm({
              message: '确认取消订单？',
            }).then(() => {
                that.cancel()
            }).catch(() => {
            })
        },

        cancel() {
            cancel({id: this.id}).then(res => {
                if (res.code !== 20000) {
                    Toast.fail({message: res.info, duration: 2000})
                } else {
                  this.getDetail()
                }
            })
        },
        accepter() {
            const that = this
            Dialog.confirm({
              message: '确认收货？',
            }).then(() => {
                that.accepterOrder()
            }).catch(() => {
            })
        },

        see(type, code) {
            const url = "http://www.kuaidi100.com/chaxun?com=" + type + "&nu=" + code
            location.href = url
        },

        accepterOrder() {
            accepter({id: this.id}).then(res => {
                if (res.code !== 20000) {
                    Toast.fail({message: res.info, duration: 2000})
                } else {
                  this.getDetail()
                }
            })
        }

    },
    activated: function () {
        this.passwordVal = ''
        const obj = {
            hasAddress: false
        }
        this.addressInfo = obj
        this.id = this.$route.query.id
        this.getDetail()

        this.$refs.head.setNavBarUrl()
    }
}
</script>

<style>
    .info .van-icon__image{
        width: 0.8rem;
        height: 0.8rem;
        border-radius: 50%;
    }
    .order_info .van-cell__title{
        flex: 0.6;
    }

</style>
<style lang="stylus" scoped>



    .content_div
        padding .3rem
        height 7rem
    .orderPay_content
        width 100%
        height 100%
        overflow hidden
        background #f5f5f5
        margin-bottom: 14%
        .orderPay_fixed
            position relative
            // top 0
            left 0
            width 100%
            padding .2rem .3rem
            overflow hidden
            background #dabb9e
            z-index: 999
            .f2
                line-height .6rem
                font-size .20rem
                color #fff
                text-align right
                display: inline-block;
                margin-left: .2rem
            .fl
                line-height .6rem
                font-size .26rem
                color #fff
                text-align right
                .van-count-down
                    line-height .6rem
                    font-size .26rem
                    color #fff
                    display inline-block
            button
                padding  0 .3rem
                height .6rem
                line-height .6rem
                border-radius 4px
                margin-left .2rem
                font-size .26rem
            .qx
                color #ffffff
                background rgb(238, 10, 36)
            .gopay
                border 1px solid #dabb9e
                color #dabb9e
                background #fff
        .orderPay_getAddr
            background #fff
            .fgx_img
                width 100%
                overflow hidden
                img
                    width 100%
</style>
